Ext.define('wmf.lib.EditorGrid', {
	extend: 'Ext.grid.Panel',
	alias: 'widget.wmfEditorGrid',
	//iconCls: 'icon-grid',
	frame: true,
	layout: 'fit',
	initComponent: function() {
		this.plugins = [];
		this.tmpParams={ start: 0, limit: this.pageSize };
		this.autoHeight = true;
		this.border = true;
		//this.forceFit = true;
		this.stripeRows = true;
		if(!this.nodeid) this.nodeid = "";
		if(!this.operationType) this.operationType = "";
		if (this.selectMulti == true) {
		this.selModel = Ext.create('Ext.selection.CheckboxModel');
		}
		if(this.checkEmpty == undefined) {
		  this.checkEmpty = false;
		}
		this.checkEmptyResult = 'pass'; //pass, empty
		if(this.bbar == undefined) {
		  this.bbar = true; 
		}
		
		var cedit;
		if(!this.edittype || (this.edittype && this.edittype == 'celledit')) {
			cedit = Ext.create('Ext.grid.plugin.CellEditing', {
				clicksToEdit: 1
			});
		} else if(this.edittype == 'rowedit') {
			cedit = Ext.create('Ext.grid.plugin.RowEditing', {
				clicksToEdit: 1
			});
		}
		this.plugins.push(cedit);
		
		this.layout = 'fit';
		
		this.createColumns();
		this.createStore();
		this.createTbar();
		this.submitcontent = "";
		this.callParent(arguments);
    },
    
    createStore: function() {
    	this.storeFields = [];
        for (var i = 0; i < this.fields.length; i++) {
            this.storeFields.push(this.fields[i].dataIndex);
        }
        
        var storeFields = [];
        for (var i = 0; i < this.fields.length; i++) {
        	var onefield = {name:this.fields[i].dataIndex, type:'string'};
        	if(this.fields[i].defaultValue) {
        		onefield.defaultValue = this.fields[i].defaultValue;
        	}
        	storeFields.push(onefield);
        }
        if(!this.idProperty) this.idProperty = 'id';
				
  		if (this.groupField) {
            this.store = new Ext.data.DirectStore({
                root: 'list',
                totalProperty: 'total',
                idProperty: this.idProperty,
                autoDestroy: true,
                fields: storeFields,
                groupField: this.groupField,
                directFn: this.directFn,
                paramsAsHash: true,
                remoteSort:this.remoteSort
            });
        } else {
            this.store = new Ext.data.DirectStore({
                root: 'list',
                totalProperty: 'total',
                idProperty: this.idProperty,
                autoDestroy: true,
                fields: storeFields,
                directFn: this.directFn,
                paramsAsHash: true, 
                remoteSort:this.remoteSort
            });
        }
    },
    
	createColumns: function() {
        var columns = [];
        if (this.isMultiSelect == true) columns.push(this.sm);
        var fields, fieldlength;
		if(this.columnfields){
        	fields = this.columnfields;
        	fieldlength = this.columnfields.length;
		}else {
			fields = this.fields;
			fieldlength = this.fields.length;
		}
		for (var i = 0; i < fieldlength; i++) {
            var field = fields[i];
            if (field.header != 'hidden') {
            	var fl = field.flex? field.flex : 1;
            	var column = {flex:fl,sortable:false, text: field.header};
            	if(field.xtype) column.xtype = field.xtype;
            	//else column.xtype = "gridcolumn";
            	if(field.dataIndex) column.dataIndex = field.dataIndex;
            	if(field.tpl) {
            		var showTpl = "this.tpls."+field.tpl;
            		column.tpl = eval(showTpl);      		
            	} else {
            		column.renderer = Ext.bind(this.renderDetail,this);
            	}
            	
            	if(field.editor) {
           			column.editor = field.editor;
           			if(column.editor.render) {
           				column.renderer = Ext.bind(column.editor.render, this, field.editor, true);
           				//example: function(val, metadata, record, rowIndex, colIndex, store, view, combo)
           			}
            	}
           			
                if(field.style) {
                	column.style = field.style;	
                }
                if (field.sortable) {
	                column.sortable = true;
                }
                columns.push(column);
            }
        }
		
        this.columns = columns;
    },
    
    renderDetail: function(val, metadata, record, rowIndex, colIndex, store, view) {
		metadata.tdAttr = 'data-qtip="' + val + '"';
		return val;
    },
    
    getSelectedRecord: function() {
        var sm = this.getSelectionModel();
        if (sm.getCount() == 0) {
            Ext.Msg.alert('警告', '请选择一行!');
            return false;
        }

        return sm.getSelections();
    },
    
    // 创建顶部工具栏
    createTbar: function() {
        this.tbar = new Ext.Toolbar();
        var cols = [];
        
        if(this.enableAdd) {
	        this.tbar.add({
	            text: '新增',
	            icon: 'resources/icons/icon_add.png',
	            handler: Ext.bind(this.addRecord, this)
	        });
	        this.tbar.add("-");
        }
        if(this.enableEdit) {
	        this.tbar.add({
	            text: '修改',
	            icon: 'resources/icons/icon_modify.png',
	            handler: Ext.bind(this.modifyRecord, this)
	        });
	        this.tbar.add("-");
        }
        if(this.enableDelete) {
	        this.tbar.add({
	            text: '删除',
	            icon: 'resources/icons/icon_deleteall.png',
	            handler: Ext.bind(this.delRecord, this)
	        });
	        this.tbar.add("-");
        }
    },
    
    setValue: function(datastr) {
    	var store = this.getStore();
    	store.loadRawData(datastr);
    },
    
    getValue: function() {
    	this.checkEmptyResult = 'pass';
		var store = this.getStore();
		var recordsLength = store.getCount();   //获取总行数
		var fieldlen = this.storeFields.length;
		var value = "[";
		var row = "";
		for(var i = 0;i < recordsLength; i++) {		
			if(i == 0) {
				row += '{';			
			} else {
				row += ',{';
			}
			
			for(var j = 0; j < fieldlen; j++) {
				var v = store.getAt(i).get(this.storeFields[j]);
				if(this.checkEmpty && v == '')
					this.checkEmptyResult = 'empty';
				if( j == 0) {
					row += '"' + this.storeFields[j] + '":"' + v + '"';
					if(j == fieldlen - 1) {
						row += "}";	
					}
				} else {
					row += ',"' + this.storeFields[j] + '":"' + v + '"';
					if(j == fieldlen - 1) {
						row += "}";	
					}
				}
					
			}
			value += row;
		}
		value += "]";
		return value;
    },
    
	addRecord: function() {
    	var Record = this.getStore().model;
    	var p = Ext.create(Record, {
			name: '',
			port: ''
		});
		this.plugins[0].cancelEdit();
		
		this.getStore().insert(0, p);
		if(this.selectMulti) {		
			this.plugins[0].startEditByPosition({row: 0, column: 1});	
		} else {
			this.plugins[0].startEditByPosition({row: 0, column: 0});
		}
    },
    
    modifyRecord: function()
    {
    	
    },
    
    delRecord: function() {
    	var sm = this.getSelectionModel();
		var selections = sm.getSelection();
		if(selections == false){
			Ext.Msg.alert('警告', '请至少选择一行!');
	        return;
		}
		var mystore = this.getStore();
		Ext.Msg.confirm('信息', '确定要删除?', function(btn){
			if(btn == 'yes') {
				mystore.remove(selections);
				for(var i = 0; i < selections.length; i++){
					wmf.shop.shopIds += selections[i].data.propertyId;
					wmf.shop.shopIds += ",";
				}
			}
		});
    },
    
    saveRecord: function() {
    	if(!this.saveFn) {
    		return;	
    	}
    	
		this.saveFn(this.getValue(), function(r, e) {
		    Ext.Msg.alert("save", "save ok");
		});
    },
    
    getSelectedRecord: function() {
        var sm = this.getSelectionModel();
        if (sm.getCount() == 0) {
            Ext.Msg.alert('警告', '请选择一行!');
            return false;
        }

        return sm.getSelection();
    }
    
});

